﻿using IService.Front;

namespace Service.Front
{
    public class RecycleReqService : BaseService<TRecycleReq>, IRecycleReqService
    {
        public RecycleReqService(IUnitOfWorkService unitOfWorkService) : base(unitOfWorkService)
        {
        }

        /// <summary>
        /// 添加或修改回收申请
        /// </summary>
        /// <param name="par"></param>
        /// <returns></returns>
        public async Task<RM_ApiResult> AddOrUpdate(TRecycleReq par)
        {
            par.Status = (int)Enum_RecycleStatus.PendingReview;
            par.CustomerId = _CurrentCustomer.Id;
            if (par.Id == 0)
            {
                par.CreateTime = DateTime.Now;
            }
            else
            {
                var o = await Get(x => x.Id == par.Id);
                if (o != null)
                {
                    par.CreateTime = o.CreateTime;
                    par.CustomerId = o.CustomerId;
                }
            }

            var result = await AddOrUpdate(par, true);

            if (result > 0)
            {
                await Add<TMessage>(new TMessage
                {
                    CreateTime = DateTime.Now,
                    CustomerId = _CurrentCustomer.Id,
                    AboutId = result,
                    IsSend = false,
                    MsgType = Enum_MessageType.RecycleReq,
                    Remark = "您有一個回收申請單待審覈，請及時處理",
                    EnRemark = "You have a recycling application form pending review, please process it in time."
                });

                await Delete<TRecycleReqHandle>(o => o.ReqId == result);

                return _ResultHelper.BuildActionSuccess();
            }
            else
            {
                return _ResultHelper.BuildActionError();
            }
        }

        public async Task<RM_ApiResult> GetPageByCurrent(int pageNo, int pageSize)
        {
            //查询条件
            var where = Expressionable.Create<TRecycleReq>().And(o => o.IsDeleted == false)
                                      .And(o => o.CustomerId == _CurrentCustomer.Id);

            var result = new RM_PageReturn<TRecycleReq>
            {
                //查询数据
                TotalCount = await _DbContext.Queryable<TRecycleReq>().Where(where.ToExpression()).CountAsync(),
                Datas = await _DbContext.Queryable<TRecycleReq>().Includes(u => u.Customer).Where(where.ToExpression()).OrderBy(o => o.Status).OrderByDescending(o => o.Id).ToPageListAsync(pageNo, pageSize)
            };

            var list = new List<TRecycleReq>();

            //补充数据
            foreach (TRecycleReq item in result.Datas)
            {
                list.Add(await GetReq(item.Id, item));
            }
            if (list?.Count > 0)
            {
                result.Datas = list;
            }

            return _ResultHelper.BuildSuccess(result);
        }

        /// <summary>
        /// 获取详情
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public new async Task<RM_ApiResult> GetItem(int key)
        {
            if (await Any(key))
            {
                var o = await _DbContext.Queryable<TRecycleReq>().Includes(u => u.Customer).FirstAsync(o => o.Id == key);
                o = await GetReq(key, o);
                return _ResultHelper.BuildSuccess(o);
            }
            else
            {
                return _ResultHelper.BuildError(Enum_SysAttributeType.Misc.NoData);
            }
        }

        private async Task<TRecycleReq> GetReq(int key, TRecycleReq o)
        {
            if (o != null)
            {
                if (o.Customer != null)
                {
                    o.MemberName = o.Customer.NickName;
                }

                o.StatusDesc = _EnumHelper.GetDescription((Enum_RecycleStatus)o.Status);
                o.RecycleReqHandle = await _DbContext.Queryable<TRecycleReqHandle>().Includes(u => u.AdminInfo).Where(o => o.ReqId == key).OrderByDescending(o => o.HandleTime).FirstAsync();

                if (o.RecycleReqHandle != null)
                {
                    o.HandleBy = o.RecycleReqHandle.AdminInfo.AdminName;
                    o.HandleTime = o.RecycleReqHandle.HandleTime;
                    o.HandleDesc = o.RecycleReqHandle.HandleDesc;
                    o.HandlePicture = o.RecycleReqHandle.HandlePicture;
                    o.HandleAttachment = o.RecycleReqHandle.HandleAttachment;
                    o.RecycleReqHandle = null;
                }

                if (o.Status > (int)Enum_RecycleStatus.PendingReview)
                {
                    o.RecycleSend = await _DbContext.Queryable<TRecycleSend>().Where(o => o.ReqId == key).FirstAsync();
                    if (o.RecycleSend != null)
                    {
                        o.RecycleSendHandle = await _DbContext.Queryable<TRecycleSendHandle>().Includes(u => u.AdminInfo).Where(x => x.ReqId == o.Id).OrderByDescending(x => x.HandleTime).FirstAsync();
                        if (o.RecycleSendHandle != null)
                        {
                            o.SendHandleBy = o.RecycleSendHandle.AdminInfo.AdminName;
                            o.SendHandleTime = o.RecycleSendHandle.HandleTime;
                            o.SendHandleDesc = o.RecycleSendHandle.HandleDesc;
                            o.SendHandlePicture = o.RecycleSendHandle.HandlePicture;
                            o.SendHandleAttachment = o.RecycleSendHandle.HandleAttachment;
                            o.SendHandleCoupon = o.RecycleSendHandle.Coupon;
                            o.RecycleSendHandle = null;
                        }
                    }
                }
            }

            return o;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<RM_ApiResult> Delete(int id)
        {
            await Update(id, o => o.IsDeleted == true);
            return _ResultHelper.BuildActionSuccess();
        }
    }
}